package com.kakavr.base.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.base.log.BaseLog;
import com.kakavr.page.constant.PaginationConstant;
import com.kakavr.result.MsgResult;

/**
 * 控制器的公共接口
 * 
 * @author gang.yang
 */
@RestController
public class BaseController extends BaseLog {

	/**
	 * 初始化分页
	 * 
	 * @param request
	 * @return
	 */
	protected Map<String, Object> initPaginationParams(HttpServletRequest request) {
		Map<String, Object> params = new HashMap<String, Object>();
		String pageNo = request.getParameter(PaginationConstant.PAGE_NO_NAME);
		String pageSize = request.getParameter(PaginationConstant.PAGE_SIZE_NAME);
		if (StringUtils.isNotBlank(pageNo)) {
			params.put(PaginationConstant.PAGE_NO_NAME, pageNo);
		}else{
			params.put(PaginationConstant.PAGE_NO_NAME, PaginationConstant.PAGE_NO_VALUE);
		}
		if (StringUtils.isNotBlank(pageSize)) {
			params.put(PaginationConstant.PAGE_SIZE_NAME, pageSize);
		}else{
			params.put(PaginationConstant.PAGE_SIZE_NAME, PaginationConstant.PAGE_SIZE_VALUE);
		}
		return params;
	}
	
	/**
	 * 异常拦截方法
	 * 
	 * @param request
	 * @param response
	 * @param ex
	 * @return
	 */
	@ExceptionHandler
	protected Map<String, Object> handlerException(HttpServletRequest request, HttpServletResponse response,
			Exception ex) {
		if(ex instanceof ValidateParamException){
			ValidateParamException vpe = (ValidateParamException) ex;
			return MsgResult.errorResult(vpe.getCode(),vpe.getMessage());
		}
		ex.printStackTrace();
		error(ex.getMessage());
		return MsgResult.exceptionResult();
	}

}
